from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings
from rest_framework.generics import GenericAPIView, CreateAPIView

from cart.utils import merge_cart_cookie_to_redis
from oauth.exceptions import QQAPIError
from oauth.models import OAuthQQUser
from oauth.utils import OAuthQQ
from oauth.serializers import OAuthQQUserSerializer
# Create your views here.


# 获取logger
import logging

logger = logging.getLogger('django')


# GET /oauth/qq/user/?code=<code>
class OAuthQQUserView(CreateAPIView):
    serializer_class = OAuthQQUserSerializer

    def post(self,request,*args,**kwargs):
        response = super().post(request, *args, **kwargs)

        # 合并购物车
        response = merge_cart_cookie_to_redis(request, self.user, response)
        return response

    # def post(self, request):
    #     """绑定ＱＱ登陆用户
    #     １．获取参数并进行校验（参数完整性，手机号格式，短信验证是否正确，access_token是否有效）
    #     ２．保存绑定ＱＱ用户的登录信息
    #         ２.1如果用户已注册，直接保存绑定信息
    #         ２.2如果用户未注册，先创建一个新用户，然后在保存绑定信息
    #     ３．返回应答
    #     """
    #     # １．获取参数并进行校验（参数完整性，手机号格式，短信验证是否正确，access_token是否有效）
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #
    #     # ２．保存绑定ＱＱ用户的登录信息
    #     #     ２.1如果用户已注册，直接保存绑定信息
    #     #     ２.2如果用户未注册，先创建一个新用户，然后在保存绑定信息
    #     serializer.save()
    #     # ３．返回应答
    #     return Response(serializer.data, status=status.HTTP_201_CREATED)

    def get(self, request):
        # 1. 获取QQ返回的code
        code = request.query_params.get('code')

        if not code:
            return Response({'message': '缺少code'}, status=status.HTTP_400_BAD_REQUEST)

        # 2.获取qq登陆用户的openid
        oauth = OAuthQQ()

        try:
            # 2.1 根据code获取access_token
            access_token = oauth.get_access_token(code)
            # 3. 根据access_token获取授权QQ用户的openid
            openid = oauth.get_openid(access_token)
        except QQAPIError as e:
            logger.error(e)
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 4. 根据`openid`查询tb_oatu_qq表，判断是否已经绑定账号
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 4.2 如果未绑定，返回token
            token = OAuthQQ.generate_save_user_token(openid)
            return Response({'access_token': token})
        else:
            # 4.1 如果已经绑定，生成JWT token信息
            user = qq_user.user
            # 补充生成记录登录状态的token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            # 生成载荷信息
            payload = jwt_payload_handler(qq_user.user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })
            return response


# GET /oauth/qq/authorization/?next=<url>
#  url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),
class QQAuthURLView(APIView):
    """
    QQ登录的url地址:
    """

    def get(self, request):
        next = request.query_params.get('next', '/')
        # 获取qq登录url地址
        oauth = OAuthQQ(state=next)
        login_url = oauth.get_login_url()

        return Response({'login_url': login_url})
